﻿using ERP.ERPModels.WorkforceManage;
using ERP.WorkforceManage.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Application.Dtos;
using Microsoft.EntityFrameworkCore;

namespace ERP.WorkforceManage
{
    public class ClassesService : IClassesService
    {
        private readonly IRepository<Classes, int> _classesRepository;

        public ClassesService(IRepository<Classes, int> classesRepository)
        {
            _classesRepository = classesRepository;
        }

        public async Task<PagedResultDto<ClassesDto>> GetListAsync(ClassesListDto input)
        {
            try
            {
                // 确保输入参数有效
                if (input == null)
                {
                    input = new ClassesListDto();
                }
                
                // 确保页码和每页条数有效
                if (input.PageIndex < 1)
                {
                    input.PageIndex = 1;
                }
                
                if (input.PageSize < 1 || input.PageSize > 100)
                {
                    input.PageSize = 10;
                }
                
                try 
                {
                    // 获取查询对象
                    var query = await _classesRepository.GetQueryableAsync();
                    
                    // 根据排班计划ID过滤
                    if (input.SchedulingPlanId.HasValue && input.SchedulingPlanId.Value > 0)
                    {
                        Console.WriteLine($"根据排班计划ID {input.SchedulingPlanId.Value} 过滤班次");
                        query = query.Where(x => x.SchedulingPlanId == input.SchedulingPlanId.Value);
                    }
                    else
                    {
                        // 如果没有指定排班计划ID，则返回未关联的班次
                        Console.WriteLine("未指定排班计划ID，返回未关联的班次");
                        query = query.Where(x => x.SchedulingPlanId == null);
                    }
                    
                    // 计算总数
                    var totalCount = await query.CountAsync();
                    
                    // 获取分页数据
                    var items = await query
                        .OrderBy(x => x.SerialNumber)
                        .Skip((input.PageIndex - 1) * input.PageSize)
                        .Take(input.PageSize)
                        .Select(x => new ClassesDto
                        {
                            Id = x.Id,
                            SerialNumber = x.SerialNumber,
                            ClassesName = x.ClassesName ?? string.Empty, // 防止空值
                            StartTime = x.StartTime,
                            EndTime = x.EndTime,
                            SchedulingPlanId = x.SchedulingPlanId
                        })
                        .ToListAsync();
                    
                    // 返回结果
                    return new PagedResultDto<ClassesDto>
                    {
                        TotalCount = totalCount,
                        Items = items
                    };
                }
                catch (Exception ex)
                {
                    // 记录详细错误
                    Console.WriteLine($"班次查询异常: {ex.Message}");
                    Console.WriteLine($"异常详情: {ex}");
                    
                    // 返回空结果，避免前端错误
                    return new PagedResultDto<ClassesDto>
                    {
                        TotalCount = 0,
                        Items = new List<ClassesDto>()
                    };
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"班次服务异常: {ex.Message}");
                
                // 如果表不存在或发生其他错误，返回空结果
                return new PagedResultDto<ClassesDto>
                {
                    TotalCount = 0,
                    Items = new List<ClassesDto>()
                };
            }
        }

        public async Task<ClassesDto> GetAsync(int id)
        {
            var entity = await _classesRepository.GetAsync(id);
            return new ClassesDto
            {
                Id = entity.Id,
                SerialNumber = entity.SerialNumber,
                ClassesName = entity.ClassesName,
                StartTime = entity.StartTime,
                EndTime = entity.EndTime
            };
        }

        public async Task<ClassesDto> CreateAsync(CreateClassesDto input)
        {
            try
            {
                if (input == null)
                {
                    throw new ArgumentNullException(nameof(input), "创建班次的输入数据不能为空");
                }
                
                // 参数验证
                if (string.IsNullOrWhiteSpace(input.ClassesName))
                {
                    throw new ArgumentException("班次名称不能为空", nameof(input.ClassesName));
                }
                
                Console.WriteLine($"CreateAsync开始创建班次: SerialNumber={input.SerialNumber}, ClassesName={input.ClassesName}, StartTime={input.StartTime}, EndTime={input.EndTime}");
                
                // 使用现在的时间作为基准，只提取时分信息
                var now = DateTime.Now;
                var today = new DateTime(now.Year, now.Month, now.Day);
                var startTime = today;
                var endTime = today;
                
                try {
                    // 解析开始时间字符串
                    if (!string.IsNullOrEmpty(input.StartTime))
                    {
                        if (input.StartTime.Contains(":"))
                        {
                            var timeParts = input.StartTime.Split(':');
                            if (timeParts.Length >= 2 && int.TryParse(timeParts[0], out int hours) && int.TryParse(timeParts[1], out int minutes))
                            {
                                startTime = today.AddHours(hours).AddMinutes(minutes);
                                Console.WriteLine($"成功解析StartTime: {startTime}");
                            }
                            else
                            {
                                Console.WriteLine($"无法解析时间部分: {input.StartTime}");
                                throw new ArgumentException($"开始时间格式无效: {input.StartTime}", nameof(input.StartTime));
                            }
                        }
                        else
                        {
                            Console.WriteLine($"开始时间格式不包含冒号: {input.StartTime}");
                            throw new ArgumentException($"开始时间格式必须为HH:mm: {input.StartTime}", nameof(input.StartTime));
                        }
                    }
                    else
                    {
                        Console.WriteLine("开始时间为空");
                        throw new ArgumentException("开始时间不能为空", nameof(input.StartTime));
                    }
                    
                    // 解析结束时间字符串
                    if (!string.IsNullOrEmpty(input.EndTime))
                    {
                        if (input.EndTime.Contains(":"))
                        {
                            var timeParts = input.EndTime.Split(':');
                            if (timeParts.Length >= 2 && int.TryParse(timeParts[0], out int hours) && int.TryParse(timeParts[1], out int minutes))
                            {
                                endTime = today.AddHours(hours).AddMinutes(minutes);
                                Console.WriteLine($"成功解析EndTime: {endTime}");
                            }
                            else
                            {
                                Console.WriteLine($"无法解析时间部分: {input.EndTime}");
                                throw new ArgumentException($"结束时间格式无效: {input.EndTime}", nameof(input.EndTime));
                            }
                        }
                        else
                        {
                            Console.WriteLine($"结束时间格式不包含冒号: {input.EndTime}");
                            throw new ArgumentException($"结束时间格式必须为HH:mm: {input.EndTime}", nameof(input.EndTime));
                        }
                    }
                    else
                    {
                        Console.WriteLine("结束时间为空");
                        throw new ArgumentException("结束时间不能为空", nameof(input.EndTime));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"时间转换异常: {ex.Message}");
                    throw new ArgumentException($"时间格式转换失败: {ex.Message}", ex);
                }
                
                Console.WriteLine($"处理后的时间: StartTime={startTime}, EndTime={endTime}");
                
                try
                {
                    var entity = new Classes
                    {
                        SerialNumber = input.SerialNumber,
                        ClassesName = input.ClassesName,
                        StartTime = startTime,
                        EndTime = endTime,
                        SchedulingPlanId = input.SchedulingPlanId
                    };
                    
                    await _classesRepository.InsertAsync(entity);
                    
                    Console.WriteLine($"CreateAsync成功创建班次: ID={entity.Id}, SchedulingPlanId={entity.SchedulingPlanId}");
                    
                    return new ClassesDto
                    {
                        Id = entity.Id,
                        SerialNumber = entity.SerialNumber,
                        ClassesName = entity.ClassesName,
                        StartTime = entity.StartTime,
                        EndTime = entity.EndTime,
                        SchedulingPlanId = entity.SchedulingPlanId
                    };
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"数据库操作异常: {ex.Message}");
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                        Console.WriteLine($"内部异常堆栈: {ex.InnerException.StackTrace}");
                    }
                    throw;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CreateAsync出错: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");
                throw;
            }
        }

        public async Task<ClassesDto> UpdateAsync(int id, UpdateClassesDto input)
        {
            try
            {
                var entity = await _classesRepository.GetAsync(id);
                
                entity.SerialNumber = input.SerialNumber;
                entity.ClassesName = input.ClassesName;
                
                // 更新排班计划ID
                if (input.SchedulingPlanId.HasValue)
                {
                    entity.SchedulingPlanId = input.SchedulingPlanId;
                }
                
                // 处理时间格式 - 从字符串转换为DateTime
                var today = DateTime.Today;
                
                // 解析开始时间字符串
                if (!string.IsNullOrEmpty(input.StartTime) && input.StartTime.Contains(":"))
                {
                    var timeParts = input.StartTime.Split(':');
                    if (timeParts.Length >= 2 && int.TryParse(timeParts[0], out int hours) && int.TryParse(timeParts[1], out int minutes))
                    {
                        entity.StartTime = today.AddHours(hours).AddMinutes(minutes);
                    }
                }
                
                // 解析结束时间字符串
                if (!string.IsNullOrEmpty(input.EndTime) && input.EndTime.Contains(":"))
                {
                    var timeParts = input.EndTime.Split(':');
                    if (timeParts.Length >= 2 && int.TryParse(timeParts[0], out int hours) && int.TryParse(timeParts[1], out int minutes))
                    {
                        entity.EndTime = today.AddHours(hours).AddMinutes(minutes);
                    }
                }
                
                await _classesRepository.UpdateAsync(entity);
                
                return new ClassesDto
                {
                    Id = entity.Id,
                    SerialNumber = entity.SerialNumber,
                    ClassesName = entity.ClassesName,
                    StartTime = entity.StartTime,
                    EndTime = entity.EndTime,
                    SchedulingPlanId = entity.SchedulingPlanId
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"UpdateAsync出错: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");
                throw;
            }
        }

        public async Task DeleteAsync(int id)
        {
            await _classesRepository.DeleteAsync(id);
        }

        public async Task<PagedResultDto<ClassesDto>> GetPagedListAsync(PagedClassesRequestDto input)
        {
            try
            {
                Console.WriteLine($"GetPagedListAsync接收到请求参数: PageIndex={input.PageIndex}, PageSize={input.PageSize}, SchedulingPlanId={input.SchedulingPlanId}");
                
                var query = await _classesRepository.GetQueryableAsync();
                
                // 如果指定了排班计划ID，则只返回该排班计划的班次
                if (input.SchedulingPlanId.HasValue && input.SchedulingPlanId.Value > 0)
                {
                    query = query.Where(c => c.SchedulingPlanId == input.SchedulingPlanId.Value);
                }
                else
                {
                    // 如果没有指定排班计划ID，则返回没有关联排班计划的班次
                    query = query.Where(c => c.SchedulingPlanId == null);
                }
                
                var count = await query.CountAsync();
                var list = await query
                    .OrderBy(c => c.SerialNumber)
                    .Skip(input.SkipCount)
                    .Take(input.MaxResultCount)
                    .ToListAsync();
                
                var items = list.Select(entity => new ClassesDto
                {
                    Id = entity.Id,
                    SerialNumber = entity.SerialNumber,
                    ClassesName = entity.ClassesName,
                    StartTime = entity.StartTime,
                    EndTime = entity.EndTime,
                    SchedulingPlanId = entity.SchedulingPlanId
                }).ToList();
                
                Console.WriteLine($"GetPagedListAsync成功获取数据: 总数={count}, 条目数={items.Count}");
                
                return new PagedResultDto<ClassesDto>
                {
                    TotalCount = count,
                    Items = items
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetPagedListAsync出错: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");
                throw;
            }
        }

        public async Task BatchDeleteAsync(List<int> ids)
        {
            try
            {
                Console.WriteLine($"BatchDeleteAsync开始批量删除班次，数量: {ids.Count}");
                
                foreach (var id in ids)
                {
                    await _classesRepository.DeleteAsync(id);
                }
                
                Console.WriteLine("BatchDeleteAsync批量删除班次成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"BatchDeleteAsync出错: {ex.Message}");
                Console.WriteLine($"异常详情: {ex}");
                throw;
            }
        }
    }
}
